<template>
  <article class="page">
    <headerbar>
      <section class="search">
        <div class="icon-search">
          <img
            src="../../../../static/images/dangjian/home/icon-search.png"
            alt=""
          />
        </div>
        <input type="text" v-model="title" placeholder="请输入关键词搜索" />
      </section>
    </headerbar>

    <section class="frame-content-sub bg-light-gray">
      <section class="d-scroll-head list-news-img bg-white">
        <cube-scroll ref="scroll" :options="options" @pulling-up="onPullingUp">
          <div
            v-if="false"
            class="item"
            @click="goDetail(item)"
            v-for="(item, index) in topList"
            :key="index"
          >
            <div class="img">
              <img
                v-if="!item.listPic"
                src="../../../../static/images/user_bg.jpg"
                alt=""
              />
              <img
                v-if="item.listPic"
                :src="tools.getImgUrl(item.listPic, true)"
                alt=""
              />
            </div>
            <div class="cont">
              <h2 class="title">
                <span class="top-flag">置顶</span>{{ item.title }}
              </h2>
              <div class="tip">
                <span>{{ item.createTime }}</span>
                <span>{{ item.source || "未知" }}</span>
                <!--          <span class="no-wrap">阅读  {{item.views || 0}}</span>-->
                <broadcast :item="item"/>
<!--                <div v-if="!tools.NotIsNull(item.ttsOssUrl)">阅读 {{ item.views || 0 }}</div>
                <div v-else-if="!getIsBroadcast(item.id)" class="horn-my" @click.stop="showAudio(item)"><i class="icon-horn"></i><div>播报</div></div>
                <div v-else-if="getIsBroadcast(item.id)" class="horn-my" @click.stop="pause()"><i class="icon-pause"></i><div>暂停</div></div>-->
              </div>
            </div>
          </div>
          <div
            class="item"
            @click="goDetail(item, index)"
            v-for="(item, index) in list"
            :key="index"
          >
            <div class="img" v-if="item.listPic">
              <img
                :src="tools.getImgUrl(item.listPic)"
                alt=""
              />
            </div>
            <div class="cont">
              <h2 class="title" v-html="item.title"></h2>
              <div class="tip">
                <span>{{ item.createTime }}</span>
                <span>{{ item.source || "未知" }}</span>
                <!--          <span class="no-wrap">阅读  {{item.views || 0}}</span>-->
                <broadcast :item="item"/>
<!--                <div v-if="!tools.NotIsNull(item.ttsOssUrl)">阅读 {{ item.views || 0 }}</div>
                <div v-else-if="!getIsBroadcast(item.id)" class="horn-my" @click.stop="showAudio(item)"><i class="icon-horn"></i><div>播报</div></div>
                <div v-else-if="getIsBroadcast(item.id)" class="horn-my" @click.stop="pause()"><i class="icon-pause"></i><div>暂停</div></div>-->
              </div>
            </div>
          </div>
          <noData v-if="!hasList() && !isLoading"></noData>
        </cube-scroll>
      </section>
    </section>
  </article>
</template>

<script>
import footerbar from "../../../components/layout/footerbar.vue";
import searchBox from "../../../components/layout/searchBox.vue";
import homeHeaderbar from "@/components/layout/homeHeaderbar.vue";
import redCloudHeadMenu from "@/components/common/redCloudHeadMenu.vue";
import Axios from "axios";
export default {
  components: { footerbar, searchBox, redCloudHeadMenu, homeHeaderbar },
  name: "redCloudHeadline",
  data() {
    return {
      pageIndex: 1,
      pageSize: 10,
      isLoading: true,
      list: [],
      topList: [],
      options: {
        pullUpLoad: true,
        scrollbar: false,
      },
      title: "",
      backData: [],
      newsDetail: {
        newsContent: null,
        files: null,
        upOrDown: null,
        collected: null,
      },
    };
  },
  created() {
    console.log(this.$route.name, "created");
    let titles = this.$route.params.title;
    if (titles && titles !== "1") {
      this.title = titles;
    }
    this.list = [];
    this.topList = [];
    //      this.loadData()
  },
  mounted() {
    console.log(this.$route.name, "mounted");
  },
  watch: {
    title(val, oldVal) {
      this.$emit("onInput", val);
      this.search();
      this.title = val
    },
  },
  destroyed() {
    this.title = ""; //清空搜索
  },
  methods: {
    /*/!*播报相关*!/
    showAudio(item){//开始播报
      let url = item.ttsOssUrl
      let title = item.title.replace(/<span([^<>]*)>(.*?)<\/span>/gi, '$2')
      window.audioPlayer.playBroadcast(title,url,item.id,true)
    },
    getIsBroadcast(id){ //获取当前的id是否是播放状态
      return (this.$store.state.PLAY_BROADCAST && this.$store.state.PLAY_BROADCAST === id)
    },
    pause(){//暂停播报
      this.$store.commit("setPLAY_BROADCAST",'pause_'+this.$store.state.PLAY_BROADCAST);
      window.audioPlayer.pause()
    },
    /!*播报相关结束*!/*/
    goDetail(item, index) {
      this.$store.state.newsDetail = this.backData[index];
      let videoDetail = [
        //合集以及新闻联播
        "684772b0d56444fa9c0db6615da935be",
        "89d50ad278c342e59b7c7e1b4afd5bb0",
        "11db89fffa614a1ca2b1502e45f09dec",
        "d006b2b5dbc343d4999336cab839fa34",
        "1d361f9b72af4c57a93ad752fcedcdb8",
        "0fe8ed7c43254d84953ec0c7714df6a5",
        "d848e28cd5a14617be976be23efed142",
        "83def6bfa8654230ad9dd10e398985e3", //新闻联播
        "7e841ccc77484535be00a3d3e205901f",
        "db96d49c341644d78a9c2743b6042ff4",
      ];
      let fmDetail = [
        //fm
        "19caaad1cae44decb23f9cc3bf28e8d8",
        "a96feccba3c849ebb046a0004a9dcba0",
        "933dda58e75342f9bf3df3c26bc6d8b0",
        "4640b23264ef4a83a609bd7b3d7af836",
        "7f14dd4a9b7246abbf9d1a750a2a42e3",
      ];
      let douyin = [
        //红云播客
        "19a64c36d6ff4442948bb99bb1a06e77",
      ];
      console.log("89d50ad278c342e59b7c7e1b4afd5bb0", item.channelId);
      if (this.isHasFocus(item.channelId, videoDetail)) {
        this.$store.state.isVideo = true;
        this.$store.state.videoDetail = item;
        this.$store.state.newsDetail = item;
        // // 缓存专辑数据
        // this.$store.state.zhuanjiList = this.list
        // 带上专辑标识，详情页进行连续播放
        this.$router.push({
          name: "videoDetail",
          query: { id: item.id, zhuanji: 1 },
        });
      } else if (this.isHasFocus(item.channelId, fmDetail)) {
        this.$store.state.isVideo = false;
        this.$store.state.videoDetail = item;
        this.$store.state.newsDetail = item;
        this.$router.push({ name: "videoDetail", query: { id: item.id } });
      } else if (this.isHasFocus(item.channelId, douyin)) {
        /* this.$store.state.newsDetail = item;
        this.tools.hideLoading();

        this.fetchVideoDetail(item).then((data) => {
          this.tools.hideLoading();
          this.$store.state.newsDetail.detail = data;
          console.log("newsDetail", this.$store.state.newsDetail);
          this.$createVideoPlayerComponent({
            $props: {
              fullName: this.nickName,
              videoUrl: this.tools.getImgUrl(data.files[0].fileId),
            },
          }).show();
        }); */

        this.tools.hideLoading();
        var me = this;
        return Axios.all([
          me.contentDetailNew(item),
          me.newsFiles(item),
          me.contentGetSfdz(item),
          me.contentGetSfsc(item),
        ])
          .then(
            Axios.spread((res1, res2, res3, res4) => {
              me.tools.hideLoading();
              me.newsDetail.newsContent = res1;
              me.newsDetail.files = res2;
              me.newsDetail.upOrDown = res3;
              me.newsDetail.collected = res4;

              item.detail = me.newsDetail;
              me.$store.state.newsDetail = item;
              console.log("playVideo", item);
              me.$createVideoPlayerComponent({
                $props: {
                  fullName: me.nickName,
                  videoUrl: me.tools.getImgUrl(res2[0].fileId),
                },
              }).show();
              return false;
            })
          )
          .catch((err) => {
            console.log(err.response);
          });
      } else {
        this.$router.push({
          name: "redCloudNewsDetail",
          params: { id: item.id },
        }).catch(err =>{console.log(err)});
      }
    },
    //获取内容详情(新)
    contentDetailNew(v) {
      let me = this;
      return me.fetchService.contentDetailNew(v.id).then((res) => {
        if (res.code === 0) {
          return res.data.newsContent;
        }
      });
    },
    //获取新闻附件
    newsFiles(v) {
      let me = this;
      return me.fetchService.newsFiles(v.id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否点赞指定的新闻
    contentGetSfdz(v) {
      let me = this;
      return me.fetchService.contentGetSfdz(v.id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    //查询当前用户是否收藏指定的新闻
    contentGetSfsc(v) {
      let me = this;
      return me.fetchService.contentGetSfsc(v.id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    fetchVideoDetail(item) {
      return this.fetchService.contentPageDetail(item.id).then((res) => {
        if (res.code === 0) {
          return res.data;
        }
      });
    },
    loadData() {
      this.isLoading = true;
      let data = {
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        title: this.title,
      };
      return this.fetchService.appIndexSearch(data).then((res) => {
        if (res.code !== 0) {
          return this.tools.alert(res.message || res.resp_msg);
        }
        this.isLoading = false;
        this.$refs.scroll.forceUpdate &&
          this.$refs.scroll.forceUpdate(true, false);
        if (this.pageIndex === 1) {
          this.list = [];
        }
        let searchReg = new RegExp(`${this.title}`, "g");
        let searchReplace = `<span class="text-red">${this.title}</span>`;
        // 备份结果集，方便后面详情传值
        this.backData = JSON.parse(JSON.stringify(res.data.page));
        res.data.page.forEach((v, i) => {
          // 标红字体
          if (this.title.length > 0) {
            v.title = v.title.replace(searchReg, searchReplace);
          }
        });
        if (this.pageIndex === 1) {
          this.list = [];
        }
        this.list = this.list.concat(res.data.page);
        this.pageIndex++;
        if (res.data.page.length === 0 && top.length === 0) {
          this.tools.tip("暂无更多");
        }
        return res;
      });
    },
    hasList() {
      return this.list.length > 0;
    },
    onPullingUp() {
      this.loadData().then((res) => {
        setTimeout(() => {
          this.$refs.scroll.forceUpdate &&
            this.$refs.scroll.forceUpdate(true, false);
          this.options.isPullUpLoad = false;
        }, 100);
      });
    },
    search() {
      console.log(this.title);
      this.$store.commit("setHomeSearchKeywords", this.title);
      if (this.title !== "" && this.title.toUpperCase() === '**TEST**') {
        this.title = '';
        this.$router.push({name: 'test'});
        return;
      }
      if (this.title !== "") {
        this.$router.replace({ path: `/indexSearch/${this.title}` });
      }
      this.list = [];
      this.pageIndex = 1;
      this.loadData();
    },
    /*判断是否存在某个值*/
    isHasFocus(userId, list) {
      let ret = false;
      list.some((v) => {
        if (v === userId) {
          ret = true;
          return false;
        }
      });
      return ret;
    },
    myIsNaN(value) {
      var regPos = /^\d+(\.\d+)?$/; //非负浮点数
      var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
      console.log("value", regPos.test(value), regNeg.test(value));
      if (regPos.test(value) || regNeg.test(value)) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/common/stylus/moon.scss";
.search {
  width: 100%;
  background: #fff;
  border-radius: pxToRem(100px);
  position: relative;
  height: pxToRem(60px);
  font-size: 14PX;
  input {
    border-radius: pxToRem(100px);
    width: 100%;
    height: pxToRem(60px);
    margin: 0;
    padding: 0 pxToRem(54px);
    border: none;
    font-size: 14PX;
    font-weight: 400;
    color: #000;
    font-family: dang;
    &::placeholder {
      font-family: inherit;
      font-size: 14PX;
    }
  }
  .icon-search {
    position: absolute;
    left: pxToRem(16px);
    top: 50%;
    transform: translateY(-50%);
    z-index: 3;
    width: pxToRem(26px);
    height: pxToRem(27px);
    img {
      @include fullImg();
    }
  }
  .icon-scan {
    position: absolute;
    right: pxToRem(16px);
    top: 50%;
    transform: translateY(-50%);
    z-index: 3;
    width: pxToRem(31px);
    height: pxToRem(29px);
    img {
      @include fullImg();
    }
  }
}
</style>

